package com.demo.core.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.base.model.PhoneMsg;
import com.demo.base.util.CommonUtil;
import com.demo.base.util.DateTimeUtil;
import com.demo.core.dao.PhoneMsgDao;

@Transactional
@Service
public class PhoneMsgService {

	private final String userName = "ZZJS000981";//账号
	private final String pwd = "zzy25897@";//密码
	private final String httpUrl = "https://sdk2.028lk.com/sdk2/BatchSend2.aspx";
	private final String  ENCODING="UTF-8";//编码

	@Autowired
	private PhoneMsgDao phoneMsgDao;
	
	@Autowired
	private SystemLogService systemLogService;
	
	/**
	 * 保存短信到数据库
	 * @param msg
	 * @return
	 */
	public void saveMsg(String phone,String content){
		if(!CommonUtil.isNull(phone)&&!CommonUtil.isNull(content)){
			PhoneMsg msg = new PhoneMsg();
			msg.setRecordCreateTime(DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd_HH_mm_ss));
			msg.setPhone(phone);
			msg.setContent(content);
			msg.setFlag("0");
			phoneMsgDao.add(msg);
		}
	}
	
	/**
	 * 使用短信设备真实发送短信
	 */
	public void sendRealmsg(){
		//把今天之前没有发送完成的短信改为发送失败
		phoneMsgDao.updateYestodayMsg();
		
		//查询待发送短信列表
		List<PhoneMsg> list=phoneMsgDao.listExpectSendSms();
		
		if(!CommonUtil.isNull(list)&&list.size()>0){
			systemLogService.addSystemLog("系统", "发送短信，一共："+list.size()+"条。");
		    CloseableHttpClient client = HttpClients.createDefault();
		    
			for (PhoneMsg sendSms : list) {
				//给短信内容加上签名
				sendSms.setContent(sendSms.getContent()+"【xxxxxxxx】");
				
				//构建表单参数
				List<NameValuePair> params=new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("CorpID", userName));//短信平台账号
				params.add(new BasicNameValuePair("Pwd", pwd));//短信平台密码
				params.add(new BasicNameValuePair("Mobile", sendSms.getPhone()));
				params.add(new BasicNameValuePair("Content", sendSms.getContent()));
				UrlEncodedFormEntity urlEncodedFormEntity=new UrlEncodedFormEntity(params, Consts.UTF_8);
				
				//设置请求和传输超时时间5秒
				RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5*1000).setConnectTimeout(5*1000).build();
				
				//创建链接
				HttpPost httpPost=new HttpPost(httpUrl);
				httpPost.setEntity(urlEncodedFormEntity);
				httpPost.setConfig(requestConfig);
				
				CloseableHttpResponse response=null;
				try {
					//发送请求
					response=client.execute(httpPost);
				}catch (Exception e) {
					systemLogService.addSystemLog("系统", "短信Http接口调用失败。");
					continue;
				}
				//response返回正常
				if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
					HttpEntity entity=response.getEntity();
					if(entity!=null){
						 int R=-2;
						 try {
							 R=Integer.parseInt(EntityUtils.toString(entity, ENCODING));
						 } catch (Exception e) {
							 systemLogService.addSystemLog("系统", "短信发送读取response响应内容失败。");
						 }
						 StringBuffer log=new StringBuffer();
						 log.append("Http接口调用成功，短信id为【"+sendSms.getId()+"】，返回码为【"+R+"】。");
						 String remark="";
						 if(R>=0){
							 remark="提交成功。";
							 //发送成功
							 PhoneMsg p = new PhoneMsg();
							 p.setId(sendSms.getId());
							 p.setFlag("1");
							 phoneMsgDao.update(p);
						 }else{
							 //发送失败
							if(R==-1){
								remark="账号未注册。";
							}else if(R==-2){
								remark="其他错误。";
							}else if(R==-3){
								remark="帐号或密码错误。";
							}else if(R==-5){
								remark="余额不足，请充值。";
							}else if(R==-6){
								remark="定时发送时间不是有效的时间格式。";
							}else if(R==-7){
								remark="提交信息末尾未签名，请添加中文的企业签名【 】。";
							}else if(R==-8){
								remark="发送内容需在1到300字之间。";
							}else if(R==-9){
								remark="发送号码为空。";
							}else if(R==-10){
								remark="定时时间不能小于系统当前时间。";
							}else if(R==-100){
								remark="限制IP访问。";
							}
							PhoneMsg p = new PhoneMsg();
							p.setId(sendSms.getId());
							p.setFlag("2");
							phoneMsgDao.update(p);
							log.append(remark);
						 }
						 //记录日志
						 systemLogService.addSystemLog("系统", log.toString());
					 }
				}else{
					systemLogService.addSystemLog("系统", "短信Http接口调用成功，但返回状态错误，错误码为【"+response.getStatusLine().getStatusCode()+"】。");
				}
			}
		}
	}
}
